package routers

import (
	"embed"
	"encoding/json"
	"net/http"

	"gitee.com/kessil/chicory/internal/config"
	"gitee.com/kessil/chicory/internal/middleware"

	"github.com/go-chi/chi/v5"
	"xorm.io/xorm"
)

func SetupRoutes(r *chi.Mux, db *xorm.Engine, cfg *config.Config, staticFiles embed.FS) {
	// 添加健康检查路由
	r.Get("/api/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"status":  "ok",
			"version": "v1",
		})
	})

	// 创建API v1路由组
	r.Route("/api/v1", func(apiV1 chi.Router) {
		// 认证路由 - 公共路由
		authRouter := NewAuthRouter(db, cfg)
		apiV1.Mount("/auth", authRouter.Routes())

		// 需要JWT验证的路由
		apiV1.Group(func(protected chi.Router) {
			// 添加JWT认证中间件
			protected.Use(middleware.JWTAuthMiddleware(cfg))

			// 用户路由
			userRouter := NewUserRouter(db, cfg)
			protected.Mount("/user", userRouter.Routes())

			// 角色路由
			roleRouter := NewRoleRouter(db, cfg)
			protected.Mount("/role", roleRouter.Routes())

			// 权限路由
			permissionRouter := NewPermissionRouter(db, cfg)
			protected.Mount("/permission", permissionRouter.Routes())

			// 资产路由
			assetRouter := NewAssetRouter(db, cfg)
			protected.Mount("/asset", assetRouter.Routes())

			// 调度台路由
			deskRouter := NewDeskRouter(db, cfg)
			protected.Mount("/desk", deskRouter.Routes())

		})
	})

	// 静态文件服务
	r.Handle("/dist/*", http.FileServer(http.FS(staticFiles)))
	r.Handle("/*", http.FileServer(http.Dir("./static")))
}
